// pages/carddetails/carddetails.js
const app = getApp()
var server = require('../../utils/server');
const baseUrls = 'http://soundlab.jschunk.com:8085';
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
const backgroundAudioManager = wx.getBackgroundAudioManager()
innerAudioContext.autoplay = true
var that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    pl: "",
    hf: "", //回复内容
    commentid: '', //评论ID
    comment: 1, //一级回复还是二级回复
    rereplyName: '', //二级回复者的姓名
    pllength: 0,
    PageIndex: 1,
    sfdz: 1,
    gz: 1,
    tu: app.globalData.tupian,
    list: [],
    pllist: [],
    img: app.globalData.tupian + '21.png',
    yinyue: app.globalData.tupian + 'yy.png',
    yinyue1: app.globalData.tupian + 'yy1.png',
    fenxiang: app.globalData.tupian + 'zf2.png',
    tx1: app.globalData.tupian + 'xxtx1.png',
    dz: app.globalData.tupian + 'dw2.png',
    sc1: app.globalData.tupian + 'sc1.png',
    dianzan: app.globalData.tupian + 'dianzan.png',
    dianzan1: app.globalData.tupian + 'dianzan1.png',
    ly: false,
    tc: 1,
    tup1: 0,
    show: false,
    hiddenmodalput: true,
    src: '',
    tphc: '',//分享图片
    appuserID: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (ee) {
    that = this
    console.log('app.globalData.userID', app.globalData.userID)
    console.log('进来的参数', ee)
    that.setData({
      appuserID: app.globalData.userID
    })
    if (ee.scene) {
      console.log('jinlai')
      const scene = decodeURIComponent(ee.scene)
      that.setData({
        id: scene
      })
      that.list(scene),
        that.ppl(scene, 1)
    } else {
      that.setData({
        show: ee.show,
        id: ee.id
      })
      that.list(ee.id),
        that.ppl(ee.id, 1)
    }
  },

  list: function (idd) {
    server.requestForm(false, 'get', 'card', {
      filter: {
        _id: { $in: [idd] }
      }
    },
      function (e) {
        console.log(e)
        if (e.data[0].createTime != undefined) {
          e.data[0].createTime = e.data[0].createTime.substr(0, 10);
        }
        for (let i = 0; i < e.data[0].likeID.length; i++) {
          if (e.data[0].likeID[i] == app.globalData.userID) {
            console.log('11')
            that.setData({
              sfdz: 2
            })
          }
        }
        that.setData({
          list: e.data[0],
          src: e.data[0].soundPath
        })
        that.user()
      })
  },

  sanc: function (e) {
    var id = e.currentTarget.dataset.id
    wx.showModal({
      title: '是否删除评论',
      // content: '模态弹窗',
      success: function (res) {
        if (res.confirm) {
          server.requestForm(false, 'delete', 'comment/' + id, {
            // id: id,
          }, function (e) {
            console.log('删除', e)
            if (e.code == 0) {
              that.ppl(that.data.id, 1)
            } else {
              wx.showToast({
                title: e.message,
                icon: 'none',
                duration: 1000,
              });
            }
          })
        } else {
          console.log('用户点击取消')
        }
      }
    })

  },

  user: function (e) {
    server.requestForm(false, 'get', 'user', {
      filter: {
        _id: app.globalData.userID
      }
    },
      function (e) {
        console.log(e)
        if (e.code == 0) {
          if (e.data[0].careID.length == 0) {
            that.setData({
              gz: 1
            })
          } else {
            for (let i = 0; i < e.data[0].careID.length; i++) {
              if (e.data[0].careID[i] === that.data.list.authorID) {
                console.log('11')
                that.setData({
                  gz: 2
                })
                return;
              }
              console.log('222')
              that.setData({
                gz: 1
              })
            }
          }
        }

      })
  },


  ClipboardData: function (e) {
    var title = e.currentTarget.dataset.title
    wx.setClipboardData({
      data: title ,
      success: function (res) {
        // wx.showModal({
        //   title: '提示',
        //   content: '复制成功',
        //   showCancel: false
        // });
      }
    })
  },

  ppl: function (idd, PageIndex) {
    server.requestForm(true, 'get', 'comment', {
      page: ({
        size: 6,
        index: PageIndex
      }),
      filter: {
        cardID: idd,
        checkState: 1
      }
    },
      function (e) {
        if (e.code == 0) {
          if (!e.data.items) {
            that.setData({
              pllist: []
            })
          } else {
            for (let i = 0; i < e.data.items.length; i++) {
              var str = e.data.items[i].createTime
              var d = new Date(str.replace(/-/g, '/'));
              console.log('dddddddd', d)
              if (d.getMinutes() < 10) {
                var Minutes = '0' + d.getMinutes()
              } else {
                var Minutes = d.getMinutes()
              }
              // var d = new Date(e.data.items[i].createTime);
              e.data.items[i].createTime = (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + Minutes;
            }
            console.log(e)
            that.setData({
              pllist: e.data.items,
              pllength: e.data.items.length,
            })
          }
        } else {
          wx.showToast({
            title: e.message,
            icon: 'none',
            duration: 1000,
          });
        }

      })
  },
  bofang1: function (e) {
    console.log('开始播放')
    backgroundAudioManager.title = that.data.list.title
    backgroundAudioManager.src = that.data.src,
      backgroundAudioManager.play()
  },
  bofang: function (e) {
    if (that.data.ly == false) {
      console.log('进来11', that.data.list.soundPath)
      innerAudioContext.src = that.data.src
      innerAudioContext.onPlay((res) => {
        console.log('开始播放', res)
      })
      innerAudioContext.onError((res) => {
        console.log('cuowu', res)
        console.log(res.errCode)
      })
      innerAudioContext.onEnded((res) => {
        console.log('结束', res)
        that.setData({
          ly: false
        })
      })
      that.setData({
        ly: true
      })
    } else {
      console.log('暂停zhanting')
      innerAudioContext.pause(() => {
        console.log('暂停')
      })
      innerAudioContext.onError((res) => {
        console.log(res.errMsg)
        console.log(res.errCode)
      })
      that.setData({
        ly: false
      })
    }
  },

  pl: function (e) {
    console.log(e)
    var pl = e.detail.value
    that.setData({
      pl: pl
    })
  },
  plfs: function (e) {
    if (that.data.pl.replace(/(^\s*)|(\s*$)/g, "") != '') {
      server.requestForm(true, 'post', 'comment', {
        cardID: that.data.list._id,
        commenterHeadPicPath: app.globalData.userInfo.avatarUrl,
        commenterName: app.globalData.userInfo.nickName,
        content: that.data.pl,
        commenterID: app.globalData.userID
      },
        function (e) {
          console.log(e)
          if (e.code != 1300) {
            that.setData({
              pl: ''
            })
            that.ppl(that.data.id, 1)
          } else {
            wx.showToast({
              title: e.msg,
              icon: 'none',
              duration: 1000,
            });
          }

        })
    } else {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none',
        duration: 1000,
      });
    }

  },
  dianzan: function (e) {
    server.requestForm(true, 'put', 'card/modifyLike', {
      _id: that.data.list._id,
      likeID: app.globalData.userID
    },
      function (e) {
        console.log(e)
        wx.showToast({
          title: e.msg,
          icon: 'none',
          duration: 1000,
          mask: true
        });
        that.setData({
          sfdz: 1
        })
        that.list(that.data.id)
      })
  },
  guanzu: function (e) {
    that.modifyCare()
  },
  modifyCare: function (e) {
    server.requestForm(true, 'put', 'user/modifyCare', {
      authorID: that.data.list.authorID,
      watcherID: app.globalData.userID
    },
      function (e) {
        console.log(e)
        wx.showToast({
          title: e.msg,
          icon: 'none',
          duration: 1000,
          mask: true
        });
        that.list(that.data.id)
      })
  },
  dz: function (e) {
    console.log(e)
    var name = e.currentTarget.dataset.name
    // wx.getLocation({
    //   type: 'gcj02', //返回可以用于wx.openLocation的经纬度
    //   success(res) {
    //     const latitude = res.latitude
    //     const longitude = res.longitude
    //     wx.openLocation({
    //       latitude,
    //       longitude,
    //       name: name,
    //       scale: 18
    //     })
    //   }
    // })
  },
  //开启弹窗
  tc: function (e) {
    this.setData({
      show: true,
      tc: 1,
    });
  },

  //关闭弹窗
  closeBanner: function () {
    this.setData({
      show: false,
      tc: 0,
    });
  },
  //修改签名
  nc: function (e) {
    var nickName = e.detail.value
    this.setData({
      hf: nickName
    })
  },
  nicheng: function (e) {
    console.log(e)
    var commentid = e.currentTarget.dataset.commentid
    var comment = e.currentTarget.dataset.comment
    if (comment == 1) {
      this.setData({
        hiddenmodalput: !this.data.hiddenmodalput,
        commentid: commentid,
        comment: comment
      })
    } else {
      var replyerName = e.currentTarget.dataset.replyername
      this.setData({
        hiddenmodalput: !this.data.hiddenmodalput,
        commentid: commentid,
        comment: comment,
        rereplyName: replyerName
      })
    }

  },
  //取消按钮  
  cancel: function () {
    this.setData({
      hiddenmodalput: true,
      commentid: '',
      comment: 1
    });
  },
  //确认  
  confirm: function (e) {
    console.log('qr')
    if (that.data.hf.replace(/(^\s*)|(\s*$)/g, "") != '') {
      if (that.data.comment == 1) {
        server.requestForm(true, 'post', 'comment/reply', {
          commentID: that.data.commentid,
          replyerName: app.globalData.userInfo.nickName,
          // rereplyName:'',
          replyerID: app.globalData.userID,
          replyContent: that.data.hf
        },
          function (e) {
            console.log(e)
            that.setData({
              hf: ''
            })
            that.cancel()
            that.ppl(that.data.id, 1)
          })
      } else {
        server.requestForm(false, 'post', 'comment/reply', {
          commentID: that.data.commentid,
          replyerName: app.globalData.userInfo.nickName,
          rereplyName: that.data.rereplyName,
          replyerID: app.globalData.userID,
          replyContent: that.data.hf,
        },
          function (e) {
            console.log(e)
            that.setData({
              hf: ''
            })
            that.cancel()
            that.ppl(that.data.id, 1)
          })
      }

    } else {
      wx.showToast({
        title: '请输入回复内容',
        icon: 'none',
        duration: 1000,
      });
    }

  },


  //生成分享大图
  datu: function (e) {
    that.setData({
      tc: 2
    })
    server.requestForm(false, 'get', 'card/makePicture', {
      filter: {
        cardID: that.data.id
      }
    },
      function (e) {
        console.log(e)
        if (e.code === 0) {
          that.setData({
            // tphc: baseUrls + e.url,
            tphc: e.url,
            tup1: 1,
          })
          console.log('data', that.data)
          return;
        } else if (e.code == 2000) {
          that.setData({
            tphc: e.url,
            tup1: 1,
          })
        } else {
          wx.showToast({
            title: e.msg,
            icon: 'none',
            duration: 1000,
          });
        }
      })
  },
  //点击保存图片
  save() {
    let that = this
    //若二维码未加载完毕，加个动画提高用户体验
    wx.showLoading({
      icon: 'loading',
      title: '正在保存图片',
    })
    //判断用户是否授权"保存到相册"
    wx.getSetting({
      success(res) {
        //没有权限，发起授权
        console.log('发起授权', res)
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {//用户允许授权，保存图片到相册
              console.log('res1111')
              that.savePhoto();
            },
            fail() {//用户点击拒绝授权，跳转到设置页，引导用户授权
              console.log('res2222')
              wx.hideLoading()
              wx.showToast({
                title: '请打开相册授权',
                icon: 'none',
                duration: 1000
              })
              wx.openSetting({
                success() {
                  wx.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success() {
                      that.savePhoto();
                    }
                  })
                }
              })
            }
          })
        } else {//用户已授权，保存到相册
          that.savePhoto()
        }
      }
    })
  },
  //保存图片到相册，提示保存成功
  savePhoto() {
    let that = this
    wx.downloadFile({
      url: that.data.tphc,
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(res) {
            wx.hideLoading()
            wx.showToast({
              title: '保存成功',
              icon: "success",
              duration: 1000
            })
          }
        })
      }
    })
  },

  onShareAppMessage: function (ops) {
    if (ops.from === 'button') {
      // 来自页面内转发按钮
      console.log(ops.target)
    }
    return {
      title: '声悦小程序',
      path: 'pages/carddetails/carddetails?id=' + that.data.list._id, // 路径，传递参数到指定页面。
      // imageUrl: '../../imgs/xx.png', // 分享的封面图
      success: function (res) {
        // 转发成功
        console.log("转发成功:" + JSON.stringify(res));
      },
      fail: function (res) {
        // 转发失败
        console.log("转发失败:" + JSON.stringify(res));
      }
    }

  }
})